<?php
namespace app\common\controller\User;

use think\facade\Cache;
use app\common\model\User;
use app\common\model\CashList;
use app\common\model\Config;
use think\facade\Db;

class UserServer
{
    /*
     *  检测用户的 质押/解押 数据是否成功
     * */
    public function lpBalance($uid){
        if(empty($uid)){
            return false;
        }
        $cronServer = new \app\common\controller\Cron\CronServer();
        return $cronServer->pledgeTranferResultRun($uid);
    }

    /*
     *  统计用户数据
     * */
    public function getPimLp($address){

         $userModel = new User();
         $cashListModel = new CashList();
         $user_info = $userModel->where("heco_address", $address)->field("id,token_amount,lp_amount")->find();
         $uid = $user_info['id'] ?? 0;
         $nowdate = date("Ymd");

         $lp_amount = $user_info['lp_amount'] ?? 0;
         $all_lp_amount = $userModel->sumLP();
         $lp_rate = getRate($lp_amount, $all_lp_amount);
         $today_all_bonus = config("dbconfig.sys.bonus_num") * 24;
         if($uid > 0){
             $my_all_bonus = $this->staticMyBonus($uid);
             $my_today_bonus = $this->staticMyBonus($uid, $nowdate);
             $cash_token_aomunt = $cashListModel->cashTokenAmount($uid);
         }
         $pool_all = (new Config())->poolAll();
         $return_data = [
             'lp_amount' => number_to_normal($lp_amount,6),
             'all_lp_amount' => number_to_normal($all_lp_amount,6),
             'lp_rate' => sprintf("%.6f", ($lp_rate ?? 0)),
             'pool_all' => number_to_normal($pool_all,6),//矿池总量
             'today_all_bonus' => number_to_normal($today_all_bonus,6),//今日产出
             'my_all_bonus' => number_to_normal($my_all_bonus ?? 0,6),
             'my_today_bonus' => number_to_normal ($my_today_bonus ?? 0,6),
             'token_amount' => number_to_normal($user_info['token_amount'] ?? 0,6),
             'cash_token_aomunt' => number_to_normal($cash_token_aomunt ?? 0,6),
         ];
         return $return_data;
    }

    /*
     *  我已挖出的代币
     * */
    public function staticMyBonus($uid = 0,$nowdate = ''){

        $where = [];
        if($uid > 0){
            $where[] = ['uid','=', $uid];
        }
        if(!empty($nowdate)){
            $where[] = ['c_date','=', $nowdate];
        }
        $token = 0;
        try {
            $cronServer = new \app\common\controller\Cron\CronServer();
            $suffix = $cronServer->getBonusTableSuffix();
            while(1){
                if($suffix < 0){
                    break;
                }
                $c_token = Db::name("bonus_detail_list{$suffix}")->where($where)->sum("token");
                $token += $c_token;
                $suffix -= 1;
            }
        }catch (\Exception $e){
        }
        return $token;
    }


    /*
     *  账户资金变动记录
     * */
    public function fundLog($fund_data){
        $uid = $fund_data['uid'];
        $money = $fund_data['money'];
        Db::startTrans();
        try {
            $userModel = new User();
            $user = $userModel->find($uid);
            if(empty($user['id'])){
                Db::rollback();
                return returnData('用户不存在');
            }
            if($money < 0 && $user['token_amount'] < abs($money)){
                Db::rollback();
                return returnData('账户余额不足');
            }
            $suffix = $this->getFundTableSuffix();
            $fund_log_table = "fund_log{$suffix}";
            $data = [
                'uid' => $uid,
                'type' => $fund_data['type'],
                'money' => $money,
                'detail' => $fund_data['detail'] ?? '',
                'note' => $fund_data['note'] ?? '',
                'c_time' => time()
            ];
            $userModel->where("id",$uid)->inc("token_amount", $money)->update();
            $id = Db::name($fund_log_table)->insertGetId($data);
            if($id > 0){
                Db::commit();
                if($id >= 990 * 10000){
                    $this->createFundLogTable();
                }
                return returnData('success',1);
            }
            Db::rollback();
            return returnData('失败');
        }catch (\Exception $e){
            Db::rollback();
            return returnData('失败');
        }
    }

    /*
     *  创建分红记录表
     * */
    public function createFundLogTable()
    {
        $suffix = $this->getFundTableSuffix();
        try {
            $suffix += 1;
            $sql = "CREATE TABLE `kulei_fund_log{$suffix}` (
              `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
              `uid` int(10) unsigned NOT NULL DEFAULT '0',
              `type` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '变动类型(1--分红；2-提现；3-提现失败退回)',
              `money` decimal(24,6) NOT NULL DEFAULT '0.000000' COMMENT '变动金额',
              `detail` varchar(250) NOT NULL DEFAULT '' COMMENT '描述',
              `note` varchar(250) NOT NULL DEFAULT '',
              `c_time` int(10) unsigned NOT NULL DEFAULT '0',
              PRIMARY KEY (`id`),
              KEY `uid` (`uid`) USING BTREE,
              KEY `type` (`type`) USING BTREE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='token变动记录';";

            Db::query($sql);
            Db::name("config")->where("k","fund_log_table_num")->update(['v' => $suffix]);
        }catch (\Exception $e){
        }
        return "kulei_fund_log{$suffix}";
    }

    public function getFundTableSuffix(){
        return Db::name("config")->where("k","fund_log_table_num")->value("v");
    }

    /*
     *  打款
     * */
    public function tranfersAction($to_address, $tranfer_num){
        try {
            $from_address = config("dbconfig.sys.tranfer_wallet_address");
            $private = config("dbconfig.sys.tranfer_wallet_private");
            $contract_address = config("dbconfig.sys.token_address");
            $heco = new \Heco();
            $txid = $heco->contractTranfer($from_address, $tranfer_num, $contract_address, $private, $to_address);
        }catch (\Exception $e){
        }
        return $txid ?? '';
    }

    /*
     *  查询转账结果
     * */
    public function querytranfersByHash($txid, $type = 1){
        $heco = new \Heco();
        return $heco->transactionReceipt($txid, $type);
    }

    /*
     *  获取可质押的LP代币余额
     * */
    public function lineLpBalance($address){
        $balance = 0;
        if(!empty($address) && checkWalletAddress($address)){
            $contract_address = config("dbconfig.sys.lp_contract_address");
            $heco = new \Heco();
            $balance = $heco->contractBalance($address, $contract_address);
        }
        return $balance;
    }

}